<?php
require_once 'config.php';

// 分页参数
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 9; // 每页显示9本图书
$offset = ($page - 1) * $per_page;

// 搜索参数
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$category = isset($_GET['category']) ? trim($_GET['category']) : '';

// 构建查询条件
$where_clause = "1=1"; // 始终为真的条件
$params = [];

if (!empty($search)) {
    $where_clause .= " AND (title LIKE ? OR author LIKE ? OR publisher LIKE ?)";
    $search_param = "%{$search}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

if (!empty($category)) {
    $where_clause .= " AND category = ?";
    $params[] = $category;
}

try {
    // 获取图书总数
    $count_sql = "SELECT COUNT(*) FROM books WHERE {$where_clause}";
    $stmt = $pdo->prepare($count_sql);
    $stmt->execute($params);
    $total_books = $stmt->fetchColumn();
    
    // 计算总页数
    $total_pages = ceil($total_books / $per_page);
    
    // 确保当前页码有效
    if ($page < 1) $page = 1;
    if ($page > $total_pages && $total_pages > 0) $page = $total_pages;
    
    // 获取图书列表
    $sql = "SELECT * FROM books WHERE {$where_clause} ORDER BY book_id DESC LIMIT {$per_page} OFFSET {$offset}";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $books = $stmt->fetchAll();
    
    // 获取所有分类
    $stmt = $pdo->query("SELECT DISTINCT category FROM books ORDER BY category");
    $categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch(PDOException $e) {
    $_SESSION['flash_message'] = "获取图书信息失败: " . $e->getMessage();
    $_SESSION['flash_type'] = "danger";
    $books = [];
    $total_pages = 0;
    $categories = [];
}

// 页面标题
$page_title = "图书列表 - 图书借阅系统";

// 引入头部
include 'header.php';
?>

<div class="container">
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h4 class="card-title mb-4"><i class="fas fa-search mr-2 text-primary"></i>图书搜索</h4>
                    <form method="get" action="books.php" class="form-inline">
                        <div class="input-group mr-2 mb-2">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i class="fas fa-book"></i></span>
                            </div>
                            <input type="text" class="form-control" name="search" placeholder="书名/作者/出版社" value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="input-group mr-2 mb-2">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i class="fas fa-tag"></i></span>
                            </div>
                            <select class="form-control" name="category">
                                <option value="">所有分类</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo htmlspecialchars($cat); ?>" <?php echo $cat === $category ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cat); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary mb-2"><i class="fas fa-search mr-1"></i> 搜索</button>
                        <?php if (!empty($search) || !empty($category)): ?>
                            <a href="books.php" class="btn btn-outline-secondary ml-2 mb-2"><i class="fas fa-undo mr-1"></i> 重置</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-book-open mr-2 text-primary"></i>图书列表</h2>
        <div>
            <span class="badge badge-pill badge-light p-2">共 <?php echo $total_books; ?> 本图书</span>
        </div>
    </div>

    <div class="row">
        <?php if (empty($books)): ?>
            <div class="col-12">
                <div class="alert alert-info">
                    <i class="fas fa-info-circle mr-2"></i> 没有找到符合条件的图书
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($books as $book): ?>
                <div class="col-md-4 mb-4">
                    <div class="card book-card h-100">
                        <div class="card-body d-flex flex-column">
                            <h5 class="card-title"><?php echo htmlspecialchars($book['title']); ?></h5>
                            <h6 class="card-subtitle mb-2 text-muted"><i class="fas fa-user-edit mr-1"></i><?php echo htmlspecialchars($book['author']); ?></h6>
                            <p class="card-text">
                                <span class="badge badge-pill badge-light text-muted mb-1"><i class="fas fa-tag mr-1"></i> <?php echo htmlspecialchars($book['category']); ?></span><br>
                                <small class="text-muted"><i class="fas fa-building mr-1"></i> 出版社: <?php echo htmlspecialchars($book['publisher']); ?></small><br>
                                <small class="text-muted"><i class="fas fa-calendar-alt mr-1"></i> 出版年份: <?php echo htmlspecialchars($book['publication_year']); ?></small>
                            </p>
                            <div class="mt-2 mb-3">
                                <?php if ($book['available'] > 0): ?>
                                    <span class="badge badge-success"><i class="fas fa-check-circle mr-1"></i> 可借阅 (<?php echo $book['available']; ?>)</span>
                                <?php else: ?>
                                    <span class="badge badge-secondary"><i class="fas fa-times-circle mr-1"></i> 已借完</span>
                                <?php endif; ?>
                            </div>
                            <div class="mt-auto">
                                <a href="book_detail.php?id=<?php echo $book['book_id']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-info-circle mr-1"></i> 查看详情</a>
                                <?php if (isLoggedIn() && $book['available'] > 0): ?>
                                    <a href="borrow.php?id=<?php echo $book['book_id']; ?>" class="btn btn-sm btn-primary"><i class="fas fa-hand-holding mr-1"></i> 借阅</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- 分页 -->
    <?php if ($total_pages > 1): ?>
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center">
                <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category); ?>" aria-label="Previous">
                            <span aria-hidden="true"><i class="fas fa-chevron-left"></i></span>
                        </a>
                    </li>
                <?php endif; ?>
                
                <?php
                // 显示页码
                $start_page = max(1, $page - 2);
                $end_page = min($total_pages, $page + 2);
                
                for ($i = $start_page; $i <= $end_page; $i++):
                ?>
                    <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category); ?>">
                            <?php echo $i; ?>
                        </a>
                    </li>
                <?php endfor; ?>
                
                <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category); ?>" aria-label="Next">
                            <span aria-hidden="true"><i class="fas fa-chevron-right"></i></span>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>
    <?php endif; ?>
</div>

<?php include 'footer.php'; ?> 